import json
from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE
# Create your views here.
"""1.购物车管理"""
class CartsView(View):
    #1.添加到购物车
    def post(self, request):
        #1.接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        #2.校验参数
        #2.1 判断参数是否齐全
        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')
        #2.2 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')
        #2.3 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseForbidden('参数count有误')
        #2.4 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')
        #3.判断是否登录
        user = request.user
        #3.1 登录redis存储
        if user.is_authenticated:
            carts_redis_client = get_redis_connection('carts')
            client_data = carts_redis_client.hgetall(user.id)
            if not client_data:
                carts_redis_client.hset(user.id, sku_id, json.dumps({'count':count, 'selected':selected}))
            #如果存在,count就进行累加
            if str(sku_id).encode() in client_data:
                child_dict = json.loads(client_data[str(sku_id).encode()].decode())
                child_dict['count'] += count
                carts_redis_client.hset(user.id, sku_id, json.dumps(child_dict))
            #如果不存在,直接创建数据
            else:
                carts_redis_client.hset(user.id, sku_id, json.dumps({'count':count, 'selected':selected}))
            return JsonResponse({'code':RETCODE.OK, 'errmsg':'已添加至购物车'})
        #3.2 未登录 cookie存储
        else:
            #用户未登录,操作cookie购物车
            cart_str = request.COOKIES.get('carts')
            #如果用户操作过cookie购物车,解密
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            #如果用户没有操作过cookie购物车,新建空字典
            else:
                cart_dict = {}
            #判断要加入购物车的商品是否已经在购物车中,如有相同商品,累加求和,反之,直接赋值
            if sku_id in cart_dict:
                origin_count = cart_dict[sku_id]['count']
                count += origin_count
            cart_dict[sku_id] = {
                'count':count,
                'selected':selected
            }
            #将carts_dict转成密文
            cookie_cart_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({'code':RETCODE.OK, 'errmsg':'添加购物车成功'})
            response.set_cookie('carts', cookie_cart_str, max_age=3600*24*30)
            return response
    #1.展示,查询购物车
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询redis购物车
            carts_redis_client = get_redis_connection('carts')
            # 获取redis中的购物车数据
            carts_data = carts_redis_client.hgetall(request.user.id)
            # 将格式转换为和cookie一样的字典,方面后面构建数据
            carts_dict = {int(data[0].decode()): json.loads(data[1].decode()) for data in carts_data.items()}
        else:
            # 用户未登录，查询cookies购物车
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * carts_dict.get(sku.id).get('count')),
            })
        context = {
            'cart_skus': cart_skus,
        }
        # 渲染购物车页面
        return render(request, 'cart.html', context)
    #3.修改购物车
    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 判断参数是否齐全
        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')
        #判断用户是否登录
        user = request.user
        #接收cookie最后的数据
        cookie_cart_str = ""
        #如果用户已登录
        if user.is_authenticated:
            #1.连接redis
            carts_redis_client = get_redis_connection('carts')
            #2.覆盖redis以前的数据
            new_data = {'count':count, 'selected':selected}
            carts_redis_client.hset(user.id, sku_id, json.dumps(new_data))
        # 如果用户未登录
        else:
            #删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                #转成字典格式
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            #覆盖以前的数据
            cart_dict[sku_id] = {
                'count':count,
                'selected':selected
            }
            #转换成密文数据
            cookie_cart_str = CookieSecret.dumps(cart_dict)
        # 构建前端的数据
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not user.is_authenticated:
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
        return response
    #4.删除购物车
    def delete(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')
        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户登录，删除redis购物车
            carts_redis_client = get_redis_connection('carts')
            # 根据用户id 删除商品sku
            carts_redis_client.hdel(user.id, sku_id)
            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else:
            #用户未登录,删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                #转成名文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            # 创建响应对象
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转成密文
                cookie_cart_str = CookieSecret.dumps(cart_dict)
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response
'''2.全选购物车'''
class CartsSelectAllView(View):
    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)
        #校验参数
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)
            #将所有商品改成True
            for carts in carts_data.items():
                sku_id = carts[0].decode()
                carts_dict = json.loads(carts[1].decode())
                if selected:
                    # 全选
                    carts_dict['selected'] = True
                else:
                    # 取消全选
                    carts_dict['selected'] = False
                carts_redis_client.hset(user.id, sku_id, json.dumps(carts_dict))
            return JsonResponse({'code':RETCODE.OK, 'errmsg':'全选购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            carts_str = request.COOKIES.get('carts')
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            if carts_str is not None:
                carts_dict = CookieSecret.loads(carts_str)
                for sku_id in carts_dict:
                    carts_dict[sku_id]['selected'] = selected
                cookie_cart = CookieSecret.dumps(carts_dict)
                response.set_cookie('carts', cookie_cart, 24 * 30 * 3600)
            return response
'''3.展示商品页面简单购物车'''
class CartsSimpleView(View):
    def get(self, request):
        user = request.user
        #如果用户已登录,查询redis购物车
        if user.is_authenticated:
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)
            # 转换格式
            cart_dict = {int(data[0].decode()): json.loads(data[1].decode()) for data in carts_data.items()}
        #如果用户未登录,查询cookie购物车
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
        #构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })
        # 响应json列表数据
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': cart_skus})